/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.builtincomponents.UQConstraints;


import com.inspur.edp.bef.api.action.validation.IValidationContext;
import com.inspur.edp.bef.api.be.IBEContext;
import com.inspur.edp.bef.api.be.IBENodeEntityContext;
import com.inspur.edp.bef.spi.action.validation.AbstractValidation;
import com.inspur.edp.cef.entity.UQConstraintConfig;
import com.inspur.edp.cef.entity.changeset.ChangeType;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;

import java.util.ArrayList;
import java.util.HashMap;

import static com.inspur.edp.cef.entity.changeset.ChangeType.*;
import static com.inspur.edp.cef.entity.changeset.ChangeType.Added;

public class UQConstraintValidator extends AbstractValidation
{
	public UQConstraintValidator(IValidationContext context, IChangeDetail change)
	{
		super(context, change);
	}

	public UQConstraintValidator(IValidationContext context, IChangeDetail change,  HashMap<String, ArrayList<UQConstraintConfig>> uqConstraintConfigs )
	{
		super(context, change);
		getContext().getBEManagerContext().getBEManager().setConstraintInfo(uqConstraintConfigs);
	}

	@Override
	protected void execute()
	{
		HashMap<String, ArrayList<UQConstraintConfig>> constraintInfos = getContext().getBEManagerContext().getBEManager().getConstraintInfo();

		if (constraintInfos.containsKey(getContext().getNodeCode()) == false)
		{
			return;
		}
		IEntityData data = null;
		switch (getChange().getChangeType())
		{
			case Added:
			case Modify:
				data = (IEntityData)((getContext().getData() instanceof IEntityData) ? getContext().getData() : null);
				break;
			case Deleted:
				data = getContext().getOriginalData();
				break;
		}
		getContext().getBEContext().addScopeParameter(
				new UQConstraintValParameter(
						GetRootContext(getContext().getBEContext()), getContext().getNodeCode(), getChange().getDataID(), getChange().getChangeType(), data));
	}

	private IBEContext GetRootContext(IBENodeEntityContext entityContext)
	{
		if (entityContext instanceof IBEContext)
		{
			return (IBEContext)((entityContext instanceof IBEContext) ? entityContext : null);
		}
		return GetRootContext(entityContext.getParentContext());
	}
}
